package com.example.capsule_netty.service;

import com.example.capsule_netty.bean.FunctionBean;
import com.example.capsule_netty.mapper.FunctionMapper;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.annotation.Resources;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Author: zhuzhiming
 * @Date: 2022/5/15 21:13
 */
@Service
public class FunctionService {

    @Resource
    FunctionMapper functionMapper;

    @Autowired
    RedisTemplate<String, String> redisTemplate;

    public String getFunctionList(String roomName) {

        if (redisTemplate.opsForValue().get(roomName + "_function") != null) {
            return redisTemplate.opsForValue().get(roomName + "_function");
        }

        List<FunctionBean> functionBeanList = functionMapper.getFunctionsByRoomName(roomName);
        if (functionBeanList == null || functionBeanList.size() == 0) {
            return new Gson().toJson(functionBeanList);
        }
        String functions = new Gson().toJson(functionBeanList);
        redisTemplate.opsForValue().set(roomName + "_function", functions, 30, TimeUnit.SECONDS);
        return functions;

    }
}
